<template>
	<view class="payment">
		<view class="payment-header"
			@click="close()">
			<view class="give">
				付款给“{{ name }}”
			</view>
			<view class="company">
				{{ company }}
			</view>
			<image :src="img" mode="" class="icon"></image>
		</view>
		<view class="payment-content">
			<view class="money">
				金额
			</view>
			<view class="price-inp">
				<view class="dollar">￥</view>
				<view v-if="keyShow&&!keyNumber" class="dollar input_fade" style="font-size:45upx;margin-left:80upx;">|</view>
				<input class="inp"
				type="text"
				disabled
				v-model="keyNumber"
				@click="keyPopClick"/>				
				<image :src="imglink + 'member/shangchu.png'" mode="" class="butt" @click="empty" v-if="keyNumber"></image>
			</view>
		</view>
		<view style="font-size: small;margin: 20px;color: red;">
			请支付成功后，点“完成”，填写孩子报名科目和信息，老师优先排课。
		</view>
		<view class="keyboard">
			<view class="keyboard-left">
				<view class="keyboard-num">
					<view v-for="(item,index) in 9" :key="index" style="display: inline-block;">
						<button class="keyboard-num-btn"
						@click="keyClick(item)">{{item}}</button>
					</view>
				</view>
				<view class="zero">
					<button class="zero-btn"
						   @click="keyClick(0)">0</button>
					<button class="radix-btn"
							@click="keyClick('.')">.</button>
				</view>
			</view>
			<view class="keyboard-func">
				<button class="backoff"
				@click="keyClick('back')">
					<image :src="imglink + 'backoff.png'" mode="" class="backoff-img"></image>
				</button>
				<button class="succ" @click="handlePay" v-if="payShow">
					付款
				</button>
				<button class="unsucc"
						v-if="!payShow">
					付款
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imglink: this.$store.state.imgLink,
				keyNumber:"",
				name: '',
				company:'广东深圳朴新教育有限公司',
				img: '',
				money:'',
				keyShow:true, // 软键盘弹窗
				payShow:false, // 付款样式
				itemAct:{},
				activity_id:0
			}
		},
		onLoad(option) {
			let pages = getCurrentPages()
			let currentPge = pages[0].$route.fullPath
			let token = option.token;
			if(token){
				uni.setStorageSync('token', token);
			}
			let store_id = parseInt(option.store_id,10);
			if(!store_id>0){
				store_id = uni.getStorageSync('store_id')
			}else{
				uni.setStorageSync('store_id', store_id)
			}
			this.activity_id= parseInt(option.activity_id)
			this.$store.commit('updateStoreId',store_id)
			if(!this.$store.getters.getToken){
				location.href = this.$store.state.URL + "/customer/user/wx_login?page=" +currentPge + '&activity_id='+this.options.activity_id + '&shared_customer_id=' + option.customer_id+"&store_id="+option.store_id
			}
			if(isNaN(option.customer_id)){
				uni.setStorageSync('shared_customer_id',0)
			}else{
				uni.setStorageSync('shared_customer_id',parseInt(option.customer_id,10))
			}
			//如果用户已登录并且通过他人分享进入
			if(this.$store.getters.getToken && uni.getStorageSync('shared_customer_id')){
				
				this.bindActivityRelation()
			}
			let data = {
				// token:this.$store.getters.getToken,
				activity_id:option.activity_id
			}
			this.$api.gain_all_act(data).then(res => {
				console.log(res)
				if(res.status){
					this.itemAct = res.list.data[0]
				}else{
					uni.showToast({
						title:res.msg,
						icon:"none",
						duration:2000
					})
				}
			}).catch(err => {
				console.log(err)
			})
			
			//用户信息
			const data1 = {
				customer_id: option.customer_id,
				store_id:this.$store.getters.getStoreId
			}
			this.$api.getCustomerInfo(data1).then(res => {
				console.log(res)
				if(res.status){
					this.img = res.data.userinfo.avatar
					this.name=res.data.userinfo.nickname
				}
			}).catch(err => {
				console.log(err)
			})
			//店铺销售信息
			const data2 = {
				token: this.$store.getters.getToken,
				customer_store_id:this.$store.getters.getStoreId
			}
			this.$api.gain_shop_msg(data2).then(res => {
				console.log(res)
				if(res.status){
					this.company=res.data.name
				}
			}).catch(err => {
				console.log(err)
			})
		},
		methods: {
			onKeyInput(event){
				this.money = event.target.value
			},
			empty(){
				this.keyNumber = '';
			},
			keyPopClick() // 打开键盘
			{
				this.keyShow=true;
			},
			close() // 隐藏键盘
			{
				this.keyShow=false;
			},
			keyClick(index)
			{
				if (index === "back") // 如果是删除按钮
				{
					this.keyNumber = this.keyNumber.substr(0, this.keyNumber.length - 1);  // 删除最后一位
				}
				else // 否则就增加
				{
					this.keyNumber=this.keyNumber+index;
				}
				// 这是保留两位小数方法
					let str = this.keyNumber;
					let len1 = str.substr(0, 1);
					let len2 = str.substr(1, 1);
					// 如果第一位是0，第二位不是点，就用数字把点替换掉
					if (str.length > 1 && len1 === 0 && len2 !== ".")
					{
						str = str.substr(1, 1);
					}
					// 第一位不能是.
					if (len1 === ".")
					{
						str = "";
					}
					// 限制只能输入一个小数点
					if (str.indexOf(".") !== -1)
					{
						let str_ = str.substr(str.indexOf(".") + 1);
						if (str_.indexOf(".") !== -1)
						{
							str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
						}
					}
					// 正则替换
					str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
					if (this.keyNumber / 1 === 1)
					{
						str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, "$1"); // 小数点后只能输 1 位
					}
					else
					{
						str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1"); // 小数点后只能输 2 位
					}
					this.keyNumber=str;
				// 这是判断是否输入，如果输入了就显示付款按钮，反之
				if(this.keyNumber)
				{
					this.payShow=true;
				}
				else
				{
					this.payShow=false;
				}
			},
			bindActivityRelation(){
				
				let data = {
					token:this.$store.getters.getToken,
					shared_customer_id:uni.getStorageSync('shared_customer_id'),
					activity_id:this.activity_id,
				}
				this.$api.bind_activity_relation(data).then(res => {
					console.log(res)
					if(res.status){
						
					}else{
						uni.showToast({
							title:res.msg,
							icon:"none",
							duration:2000
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			handlePay(){
				const that = this
				console.log(this.keyNumber)
				if(!parseFloat(this.keyNumber)>0){
					uni.showToast({
						title: '金额必须为正数',
						duration: 2000,
						icon: "none",
						position: "top",
						mask: true
					});
					return false
				}
				let selectCourses=[]
				selectCourses.push({
					activity_course_id:this.itemAct.course_msg[0].activity_course_id,
					name:this.itemAct.name,
					image:this.itemAct.image[0],
					price:this.keyNumber,
					quantity: 1,
					cash_shopping_card_amount: 0,
				})
				let shareCustomerId = uni.getStorageSync('shared_customer_id')
				if(!parseInt(shareCustomerId,10)>0){
					shareCustomerId = 0
				}
				const data = {
					token:this.token,
					activity_id: this.itemAct.activity_id,
					telephone:"",
					buy_method:4,
					money:this.keyNumber,
					coupon_id:0,
					order_id: 0,//团购邀请
					shared_customer_id: shareCustomerId,
					courses:JSON.stringify(selectCourses),
					// #ifdef H5
					in_type:'H5',
					// #endif
					// #ifdef MP-WEIXIN
					in_type:'min',
					// #endif
				}
				
				this.$api.add_order(data).then(res => {
					console.log(res,'add_order')
					if(res.status){
						const orderId = res.order_id
						
						if(res.actual_total>0){
							console.log('应付金额为' + res.actual_total+'，执行支付');
							const data = JSON.parse(res.data)
							console.log(data)
							console.log(that.$store.getters.getStoreId)
							console.log(orderId)
							if (typeof WeixinJSBridge == "undefined"){
							   if( document.addEventListener ){
							       document.addEventListener('WeixinJSBridgeReady', 
							that.jsApiCall(that.$store.getters.getStoreId,orderId,JSON.parse(data.payInfo)), false);
							   }else if (document.attachEvent){
							       document.attachEvent('WeixinJSBridgeReady', 
							that.jsApiCall(that.$store.getters.getStoreId,orderId,JSON.parse(data.payInfo))); 
							       document.attachEvent('onWeixinJSBridgeReady', 
							that.jsApiCall(that.$store.getters.getStoreId,orderId,JSON.parse(data.payInfo)));
							   }
							}else{
							   
							   that.jsApiCall(that.$store.getters.getStoreId,orderId,JSON.parse(data.payInfo))
							}
						}
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:2000
						})
					}
					
				}).catch(err => {
					
					uni.showToast({
						title:err.errMsg,
						icon:'none',
						duration:2000
					})
				})
			},
			// 调用微信JS api 支付
			jsApiCall(storeId,orderId,jsonWechat) {
				let redirectUrl = '/pages/memberCenter/collectioncode/collectioncode/registration?store_id='+storeId+'&order_id='+orderId
				uni.setStorageSync('redirectUrl',redirectUrl)
				// alertMessage("调用微信JS api 支付"+JSON.stringify(jsonWechat));
				// alertMessage(jsonWechat+"===appId="+jsonWechat.appId+"===ss.paySign="+jsonWechat.paySign+"===ss.nonceStr="+jsonWechat.nonceStr+"===ss.signType"+jsonWechat.signType+"===ss.timeStamp"+jsonWechat.timeStamp+"===ss.package"+jsonWechat.package, 1);
				console.log(typeof jsonWechat,'jsonWechat')
				console.log(jsonWechat.appId,'jsonWechat.appId')
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
					"appId" : jsonWechat.appId,
					"nonceStr" : jsonWechat.nonceStr,
					"package" : jsonWechat.package,
					"paySign" : jsonWechat.paySign,
					"signType" : jsonWechat.signType,
					"timeStamp" : jsonWechat.timeStamp
				},res=>{
					// alert(JSON.stringify(res));
					
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						uni.redirectTo({
							url:'/pages/memberCenter/collectioncode/collectioncode/registration?store_id='+storeId+'&order_id='+orderId,
						})
						
					} else {
						
						// uni.showToast({
						// 	title:'取消支付',
						// 	icon:'none',
						// 	duration:2000
						// })
					}
				});
			}
		}
	}
</script>

<style>
	/* input { pointer-events: none; } */
	.payment{
		position: fixed;
		height: 100%;
		width: 100%;
		background-color: #ffffff;
	}
	button{
		outline: none;
		border: none;
	}
	.keyboard-left{
		position: relative;
		display: inline-block;
	}
	.keyboard{
		position: fixed;
		bottom: 0;
		left: 0;
		font-size: 0;
		width: 100%;
		background-color: #F7F7F7;
		padding-bottom: 17upx;
	}
	.payment-header{
		width: 100%;
		height: 194upx;
		overflow: auto;	
		background-color: #F7F7F7;
	}
	.give{
		margin-top: 48upx;
		margin-left: 30upx;
		font-size: 36upx;
	}
	.company{
		margin-top: 8upx;
		margin-left: 30upx;
		font-size: 28upx;
		color: #999999;
		letter-spacing: 0;
	}
	.payment-header .icon{
		position: absolute;
		top: 43upx;
		right: 16upx;
		width: 116upx;
		height: 116upx;
		border-radius: 58upx;
	}
	.payment-content{
		overflow: auto;
		width: 100%;
		/* height: 550upx; */
		border-radius: 32upx 32upx 0 0;
		background-color: #ffffff;
	}
	.money{
		margin-top: 48upx;
		margin-left: 30upx;
		overflow: auto;	
		font-size: 28upx;
		color: rgba(0,0,0,0.85);
		letter-spacing: 0;
	}
	.price-inp{
		margin-top: 24upx;
		margin-left: 30upx;
		border-bottom: 1upx solid #DEDEDE;
		font-size: 0;
	}
	.dollar{
		width:10upx;
		display: inline-block;
		font-family: PingFangSC-Semibold;
		font-size: 80upx;
		font-weight: bold;
		color: rgba(0,0,0,0.85);
		vertical-align: middle;
	}
	.price-inp .inp{
		display: inline-block;
		margin-left: 90upx;
		caret-color: orange;
		width: 500upx;
		font-size: 80upx;
		font-weight: bold;
		color: rgba(0,0,0,0.85);
		letter-spacing: 0;
		vertical-align: middle;
	}
	.butt{
		position: absolute;
		margin-top: 35upx;
		right: 34upx;
		display: inline-block;
		width: 36upx;
		height: 36upx;
	}
	.keyboard-num{
		overflow: auto;
		width: 566upx;
	}
	.keyboard-num-btn{
		margin-top: 14upx;
		margin-left: 14upx;
		width: 170upx;
		height: 87upx;
		font-weight: bold;
		border-radius: 8upx;
		background-color: #ffffff;
	}
	.keyboard-func{
		/* position: absolute; */
		display: inline-block;
		overflow: auto;
		top: 755upx;
		right: 14upx;
		vertical-align: top;
		margin-top: 14upx;
	}
	.backoff{
		width: 170upx;
		height: 87upx;
		border-radius: 8upx;
		background-color: #ffffff;
	}
	.backoff-img{
		width: 60upx;
		height: 60upx;
		margin-top: 14upx;
	}
	.succ{
		width: 170upx;
		height: 286upx;
		line-height: 290upx;
		margin-top: 14upx;
		color: #ffffff;
		border-radius: 8upx;
		background-image: linear-gradient(136deg, #FE9543 0%, #FF664F 100%);
	}
	.unsucc{
		width: 170upx;
		height: 286upx;
		color: #ffffff;
		line-height: 280upx;
		margin-top: 14upx;
		border-radius: 8upx;
		background-color: #F6CDAB;
	}
	.zero{
		margin-top: 14upx;
		margin-left: 14upx;
	}
	.zero-btn{
		display: inline-block;
		width: 354upx;
		height: 87upx;
		background-color: #ffffff;
	}
	.radix-btn{
		display: inline-block;
		margin-left: 14upx;
		width: 170upx;
		height: 87upx;
		background-color: #ffffff;
	}
	.input_fade{
		animation: fade 1000ms infinite;
		-webkit-animation: fade 1000ms infinite;
	}
	@keyframes fade {
	    from {
	        opacity: 1.0;
	    }
	    50% {
	        opacity: 0.4;
	    }
	    to {
	        opacity: 1.0;
	    }
	}
	
	@-webkit-keyframes fade {
	    from {
	        opacity: 1.0;
	    }
	    50% {
	        opacity: 0.4;
	    }
	    to {
	        opacity: 1.0;
	    }
	}
</style>
